<?php

namespace services\user;

use api\modules\mini\forms\user\UserFeedbackForm;
use common\components\Service;
use common\helpers\CommonHelper;
use common\helpers\DateHelper;
use common\models\patient\Patient;
use common\models\user\UserFeedback;
use services\log\LogMemberOpService;
use services\patient\PatientService;
use Yii;
use yii\db\Exception;

class UserFeedbackService extends Service
{
    /**
     * 客户意见列表【小程序】
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0): array
    {
        $query = UserFeedback::find()
            ->alias('uf')
            ->select([
                'uf.*',
                'p.name patient_name', 'p.mobile patient_mobile'
            ])
            ->innerJoin(Patient::tableName() . ' p', 'uf.patient_id = p.id')
            ->where([
                'uf.user_id' => Yii::$app->user->identity->member_id,
                'p.status' => Patient::STATUS_ENABLE,
            ]);

        // 排序
        $order = [
            'uf.created_at' => SORT_DESC,
            'uf.id' => SORT_DESC,
        ];
        return $this->getListPageRes($query, $page, $pageSize, $order);
    }

    /**
     * 格式化列表
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data = []): array
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'content' => $row['content'],
                'is_reply' => $row['is_reply'],
                'reply_content' => $row['reply_content'],
                'patient_name' => $row['patient_name'],
                'patient_mobile' => $row['patient_mobile'],
                'created_at_str' => DateHelper::timestampToDate($row['created_at'], DateHelper::DATE_FORMAT_4),
                'reply_time_str' => DateHelper::timestampToDate($row['reply_time'], DateHelper::DATE_FORMAT_4),
            ];
        }
        return $list;
    }

    /**
     * 意见反馈获取信息
     * @return array[]
     */
    public function getInfo(): array
    {
        $patientService = new PatientService();
        $data = $patientService->getListPage();
        $patient = [];
        foreach ($data['list'] as $row) {
            $patient[] = [
                'value' => $row['id'],
                'label' => $row['name'].'-'.$row['mobile']
            ];
        }
        return [
            'condition' => [
                'patient' => $patient
            ],
        ];
    }

    /**
     * 客户意见列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @param int $isReport
     * @return array
     */
    public function userFeedbackList(array $params, int $page, int $pageSize, int $isReport = 0): array
    {
        $query = UserFeedback::find()
            ->alias('uf')
            ->select([
                'uf.*',
                'p.name patient_name', 'p.mobile patient_mobile'
            ])
            ->innerJoin(Patient::tableName() . ' p', 'uf.patient_id = p.id and p.status = ' . Patient::STATUS_ENABLE);
        // 搜索客户意见手机号、姓名
        if (isset($params['keywords']) && $params['keywords']) {
            if (is_numeric($params['keywords'])) {
                $query->andWhere(['like', 'p.mobile', "{$params['keywords']}%", false]);
            } else {
                $query->andWhere(['like', 'p.name', $params['keywords']]);
            }
        }
        // 开始时间
        if (isset($params['created_stime']) && $params['created_stime']) {
            $query->andWhere(['>=', 'uf.created_at', strtotime($params['created_stime'])]);
        }
        // 结束时间
        if (isset($params['created_etime']) && $params['created_etime']) {
            $query->andWhere(['<=', 'uf.created_at', strtotime($params['created_etime'] . ' 23:59:59')]);
        }
        // 状态
        if (isset($params['is_reply']) && is_numeric($params['is_reply'])) {
            $query->andWhere(['uf.is_reply' => $params['is_reply']]);
        }
        if ($isReport) {
            return $query->asArray()->all();
        }
        $list = $this->getListPageRes($query, $page, $pageSize, ['uf.is_reply' => SORT_ASC, 'uf.id' => SORT_DESC]);
        foreach ($list['list'] as &$val) {
            $val['is_reply_name'] = UserFeedback::$reply[$val['is_reply']] ?? '';
            $val['created_at_str'] = $val['created_at'] ? date('Y-m-d H:i', $val['created_at']) : '';
            $val['reply_time_str'] = $val['reply_time'] ? date('Y-m-d H:i', $val['reply_time']) : '';
        }
        return $list;
    }

    /**
     * 状态下拉筛选项
     * @return array[]
     */
    public static function getReplyCondition(): array
    {
        return [
            ['value' => UserFeedback::IS_REPLY_YES, 'label' => UserFeedback::$reply[UserFeedback::IS_REPLY_YES]],
            ['value' => UserFeedback::IS_REPLY_NO, 'label' => UserFeedback::$reply[UserFeedback::IS_REPLY_NO]],
        ];
    }

    /**
     * 客户意见回复
     *
     * @param $params
     * @return array
     * @throws Exception
     */
    public function reply($params): array
    {
        $userFeedbackIs = UserFeedback::findOne($params['id']);
        if (!$userFeedbackIs) {
            return CommonHelper::api(422, '客户意见不存在');
        }
        if (empty($params['reply_content'])) {
            $isReply = UserFeedback::IS_REPLY_NO;
        } else {
            $isReply = UserFeedback::IS_REPLY_YES;
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            UserFeedback::updateAll([
                'is_reply' => $isReply,
                'reply_content' => $params['reply_content'],
                'reply_member_id' => Yii::$app->user->identity->member_id,
                'reply_time' => time(),
                'updated_at' => time(),
            ], ['id' => $params['id']]);

            // 添加日志
            LogMemberOpService::createUserReplyLog('reply', UserFeedback::findOne($params['id']));
            $transaction->commit();
            return ['id' => $params['id']];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 导出
     *
     * @param $params
     * @return string
     */
    public function export($params): string
    {
        if (!$params) {
            return CommonHelper::api(422, '暂无数据');
        }
        $data['title'] = [
            '编号',
            '客户',
            '手机号',
            '状态',
            '意见内容',
            '创建时间',
            '回复内容',
            '回复时间',
        ];

        foreach ($params as $v) {
            $temp =  [
                'id' => $v['id'],
                'patient_name' => $v['patient_name'],
                'patient_mobile' => $v['patient_mobile'],
                'is_reply_name' => UserFeedback::$reply[$v['is_reply']] ?? '',
                'content' => $v['content'],
                'created_at_str' => $v['created_at'] ? date('Y-m-d H:i', $v['created_at']) : '',
                'reply_content' => $v['reply_content'],
                'reply_time_str' => $v['reply_time'] ? date('Y-m-d H:i', $v['reply_time']) : '',
            ];
            $data['data'][] = $temp;
        }
        return $this->exportCsv($data);
    }

    /**
     * 生成excel
     *
     * @param $data
     * @param string $fileName
     * @return string
     */
    public function exportCsv($data, string $fileName = ''): string
    {
        $fileName = 'data_' . $fileName . time() . rand(1000, 9999) . '.csv';
        if (!file_exists('tmpfile')) mkdir('tmpfile');
        $file = 'tmpfile/' . $fileName;
        $fp = fopen($file, 'w');
        if ($data['title']) {
            fputcsv($fp, $data['title']);
        }
        foreach ($data['data'] as $r) {
            fputcsv($fp, $r);
        }
        fclose($fp);
        $str = file_get_contents($file);
        // file_put_contents($file, iconv("UTF-8", "GB2312//IGNORE", $str));
        file_put_contents($file, mb_convert_encoding($str, "GBK", "UTF-8"));
        return $file;
    }

    /**
     * 编辑提现账号
     * @param UserFeedbackForm $model
     * @return void
     * @throws \Exception
     */
    public static function create(UserFeedbackForm $model): void
    {
        try {
//            $transaction = Yii::$app->db->beginTransaction();

            // 1.新增反馈
            $userFeedback = new UserFeedback();
            $userFeedback->user_id = Yii::$app->user->identity->member_id;
            $userFeedback->patient_id = $model->patient_id;
            $userFeedback->content = $model->content;
            $userFeedback->is_reply = UserFeedback::IS_REPLY_NO;
            $userFeedback->saveAndCheckResult();

//            $transaction->commit();
        } catch (\Exception $e) {
//            $transaction->rollBack();
            throw $e;
        }
    }
}